package com.sinodata.bsm.cicp.finder.jboss;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.management.ObjectName;

import org.apache.log4j.Logger;
import org.jboss.jmx.adaptor.rmi.RMIAdaptor;

import com.sinodata.bsm.cicp.finder.Finder;
import com.sinodata.bsm.cicp.util.RmiUtil;

/**
 * 对Jboss Web模块的发现
 */
public class WebFinder extends Finder {

    private static final Logger logger = Logger.getLogger(WebFinder.class);

    public String splitStr(String str) {
        String s[] = str.split("name=");
        if (s.length == 2) {
            return s[1].substring(0, s[1].indexOf(","));
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<String[]> find(String ip, Map params) {
        String port = (String) params.get("PORT");
        List<String[]> list = new ArrayList<String[]>();
        try {
            RMIAdaptor rmiAdapter = RmiUtil.getRmiAdaptor(ip, Integer.parseInt(port));
            Set<ObjectName> managers = RmiUtil.queryObjectNames(rmiAdapter, "jboss.web:j2eeType=WebModule,*");
            for (ObjectName objectName : managers) {
                String managerName = (String) rmiAdapter.getAttribute(objectName, "objectName");
                String tmpName = splitStr(managerName);
                String[] info = new String[4];
                list.add(info);
                info[0] = ip + "_JbossWeb_" + tmpName;
                info[1] = tmpName;
                info[2] = ip + "_JbossWeb_" + tmpName;
                info[3] = managerName; //名称
            }
            return list;
        } catch (Exception e) {
            logger.error("failed to find jboss ManagedConnectionPool ", e);
        }
        return null;
    }

}
